/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.view;

import ohos.agp.components.Component;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import org.yczbj.ycvideoplayer.ResourceTable;

import java.io.InputStream;
import java.util.Optional;

/**
 * @since 2021-09-22
 */
public class MySurfaceView extends SurfaceProvider {
    private EventHandler handler;
    float m_circle_r = 10;
    int width = 0;
    float height = 0;
    boolean flag;
    Context context;

    public MySurfaceView(Context context) {
        super(context);
        this.context = context;
        width = getWidth();
        height = getHeight();
        handler = new EventHandler(EventRunner.getMainEventRunner());
        DrawTask drawTask = new DrawTask() {
            @Override
            public void onDraw(Component component, Canvas mCanvas) {
                if (mCanvas != null) {
                    Paint paint = new Paint();
                    paint.setAntiAlias(true);
                    paint.setColor(Color.BLUE);
                    paint.setStrokeWidth(10);
                    paint.setStyle(Paint.Style.FILL_STYLE);
                    if (m_circle_r >= (getWidth() / 10)) {
                    } else {
                        m_circle_r++;
                    }
                    PixelMap icon = getPixelMap(ResourceTable.Media_ic_palyer_share);
                    mCanvas.drawPixelMapHolder(new PixelMapHolder(icon), 0, 0, paint);

                    for (int i = 0; i < 5; i++) {
                        for (int j = 0; j < 8; j++) {
                            mCanvas.drawCircle(
                                (width / 5) * i + (width / 10),
                                (height / 8) * j + (height / 16),
                                m_circle_r, paint);
                        }
                    }
                }
            }
        };

        // 创建一个线程对象
        Thread t = new Thread(()->{
            while (flag) {
                try {
//                    synchronized (mHolder) {
                    // 让线程休息100毫秒
                    Thread.sleep(100);
                    // 调用自定义画画方法
                    handler.postTask(() -> {
                        addDrawTask(drawTask);
                    });

//                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                }
            }
        });
        // 把线程运行的标识设置成true
        flag = true;
        // 启动线程
        t.start();

        getSurfaceOps().get().addCallback(new SurfaceCallBack());


    }

    class SurfaceCallBack implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps callbackSurfaceOps) {
        }

        @Override
        public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
            flag = false;
        }
    }

    @Override
    public void pinToZTop(boolean toTop) {
        super.pinToZTop(true);
    }

    @Override
    public void removeFromWindow() {
        super.removeFromWindow();
    }

    @Override
    public Optional<SurfaceOps> getSurfaceOps() {
        return super.getSurfaceOps();
    }

    private PixelMap getPixelMap(int resId) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(drawableInputStream, sourceOptions);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (Exception e) {
            e.getLocalizedMessage();
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (Exception e) {
                e.getLocalizedMessage();
            }
        }
        return null;
    }

    /**
     * 获取屏幕宽度
     *
     * @return 屏幕宽度
     */
    public int getWidth() {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        Point point = new Point();
        display.getSize(point);
        return (int) point.getPointX();
    }

    /**
     * 获取屏幕高度，不包含状态栏的高度
     *
     * @return 屏幕高度，不包含状态栏的高度
     */
    public int getHeight() {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        Point point = new Point();
        display.getSize(point);
        return (int) point.getPointY();
    }


}
